<template>
  <!-- hideOnSinglePage：是否隐藏页码
      :datasource="accounts"
   -->
  <ele-pro-table
    ref="table"
    size="mini"
    :columns="columns"
    :datasource="datasource"
    :selection.sync="selection"
    :need-page="true"
    :hideOnSinglePage="false"
  >
    <!--头部按钮-->
    <template v-slot:toolbar>
      <div class="btn-class">
        <!--style="background: #1E6CEB;"-->
        <el-button type="primary" @click="addAccredit">
          <!--          {{accountForm.type}} == this.types -->
          添加授权
        </el-button>
        <el-button type="primary" @click="allGroups">
          批量分组
        </el-button>
        <!--style="background: #1E6CEB;"-->
        <el-button type="primary" @click="inspectionStatus" v-if="accountForm.type==2">
          检验状态
        </el-button>
        <el-button type="danger" @click="delMoreAccount">
          删除
        </el-button>
      </div>
    </template>
    <!-- 头像列 -->
    <template v-slot:head="{ row }">
      <div style="line-height: 1">
        <el-avatar v-if="row.head" :src="row.head" :size="35" />
      </div>
    </template>
    <!--分组-->
    <template v-slot:groupName="{ row }">
      <el-button type="text"> {{row.groupName || '--' }} </el-button>
    </template>
    <!--    预计到期时间-->
    <template v-slot:createTime="{ row }">
      <div class="flex-column" v-if="row.expiresIn || row.refreshExpiresIn">
        <!--        <div>11=-{{msToDate(new Date()).hasTime}}</div>-->
        <!--        <div>22=&#45;&#45;{{date(row.createTime,row.expiresIn)}}</div>-->
        <div class="v-icon" v-if="isEmpower(row)">已授权</div>
        <div class="expired-icon" v-else>已失效</div>
        <!--row.type //  1D音2K手-->
        <!--createTime :授权预计到期时间 -->
        <div>{{row.type==1 ? date(row.createTime,row.expiresIn) : date(row.createTime,row.refreshExpiresIn) }}</div>
      </div>
      <div class="flex" v-else>--</div>
    </template>
    <!--橱窗 (K手没有挂载橱窗)：1D音2K手-->
    <template v-slot:fansManage="{ row }">
      <div class="flex" v-if="row.type==1">
        <!--fansManage 是否可以挂载橱窗 0不可1可以-->
        <img style="width: 32px;height: 32px;" :src="row.fansManage==1 ? require('../../../../../assets/showcase.png') : require('../../../../../assets/no-showcase.png')" />
      </div>
      <div class="flex" v-else>--</div>
    </template>
    <template v-slot:authExTime="{ row }">
      <div class="flex" v-if="row.type==2">
        {{row.authExTime}}
      </div>
      <div class="flex" v-else>--</div>
    </template>

    <!--操作-->
    <template v-slot:action="{ row }">
      <div class="flex-around">
        <el-link
          type="primary"
          :underline="false"
          @click.stop="worksClick(row)"
        >
          作品
        </el-link>
        <el-link
          type="primary"
          :underline="false"
          @click.stop="groupClick(row)"
        >
          {{row.groupId ? '换组' : '分组'}}
        </el-link>
        <el-link
          v-if="row.type==1 && accountForm.type==2 "
          type="primary"
          :underline="false"
          @click.stop="reauthorization(row)"
        >
          <!--          无痕授权-->
          cookie授权
        </el-link>
        <el-dropdown placement="bottom" trigger="click">
          <el-link
            type="primary"
            :underline="false"
          >
            更多
          </el-link>
          <template v-slot:dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click.native="delUser(row)">删除授权</el-dropdown-item>
              <!--row.type //  1D音2K手-->-->
              <el-dropdown-item @click.native="reauthorizationMore(row)" v-if="row.type==1 && msToDate(new Date()).hasTime >= date(row.createTime,row.expiresIn)">重新授权</el-dropdown-item>
              <el-dropdown-item @click.native="reauthorizationMore(row)" v-if="row.type==2 && msToDate(new Date()).hasTime >= date(row.createTime,row.refreshExpiresIn)">重新授权</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </template>

    <!--关闭回调   :before-close="handleClose"-->
    <!--从右往左标题-->
    <el-drawer
      title="作品"
      size="70%"
      :visible.sync="showEdit"
      :direction="direction">
      <div>
        <div class="flex-between top-padding">
          <div class="flex-align-center" style="padding-right: 200px;border-right: 1px solid #F5F5F5;">
            <el-image :src="current.head" class="avatar"></el-image>
            <div class="flex-columns">
              <div class="flex-align-center">
                <div class="color333 font-overflow" style="margin-right: 48px;max-width: 300px;">{{current.nickname}}</div>
                <div class="colorA1 flex-align-center" v-if="accountForm.type==2 && current.fansManage==1">
                  <img style="width: 18px;height: 18px;margin-right: 4px" :src="require('../../../../../assets/showcase.png')" />挂载橱窗</div>
              </div>
              <div class="end-time flex-align-center">
                <div class="empower" v-if="isEmpower(current)">已授权</div>
                <div class="expire" v-else>已失效</div>
                <!--current.type //  1D音2K手-->
                {{current.type==1 ? date(current.createTime,current.expiresIn) : date(current.createTime,current.refreshExpiresIn) }} 到期
              </div>
            </div>
          </div>
          <div class="flex-align-center flex1" style="margin-left: 150px;">
            <div class="flex-column numberCount">
              <span>曝光量</span>
              <div>{{playCount || 0}}</div>
            </div>
            <div class="flex-column numberCount">
              <span>点赞数</span>
              <div>{{diggCount || 0}}</div>
            </div>
            <div class="flex-column numberCount">
              <span>评论数</span>
              <div>{{commentCount || 0}}</div>
            </div>
          </div>
        </div>
        <el-button icon="el-icon-refresh-right" type="primary" class="btn-refresh" @click="dataRefresh(current)">数据刷新</el-button>
        <div class="m-table">
          <!--toolkit：大小，行数，是否全屏展示，不加，则会展示全部（包含刷新）-->
          <!--
            element-loading-text="拼命加载中"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.8)"-->
          <ele-pro-table
            ref="tableChild"
            v-loading="loading"
            :toolkit="[]"
            size="mini"
            :columns="childColumn"
            :datasource="childUsers"
            :selection.sync="childSelect"
            :need-page="true"
            :hideOnSinglePage="false"
          >
            <template v-slot:toolbar>
              <div class="flex-align-center">
                <div v-for="(i,j) in stautsList" :key="j" @click="stautsClick(j)" :class="stautsIndex==j ? 'sel-stauts-class' : 'stauts-class' ">{{i.name}}</div>
              </div>
            </template>
            <!--昵称-->
            <template v-slot:nickname="{ row }">
              <div class="flex-columns">
                <div class="top-class flex" v-if="row.isTop==true">置顶</div>
                <div class="font-overflow">{{row.title}}</div>
              </div>
            </template>
            <!--曝光量-->
            <template v-slot:playCount="{ row }">
              <div>{{ row.taskStatus==0 ? 0 : row.exposureAmount ? row.exposureAmount : 0}}</div>
            </template>
            <!--点赞数-->
            <template v-slot:diggCount="{ row }">
              <div>{{ row.taskStatus==0 ? 0 : row.upvoteAmount ? row.upvoteAmount : 0}}</div>
            </template>
            <!--评论数-->
            <template v-slot:commentCount="{ row }">
              <div>{{ row.taskStatus==0 ? 0 : row.commentAmount ? row.commentAmount : 0}}</div>
            </template>
            <!--执行status-->
            <!--          taskStatus:0,未发布，则默认重置曝光量等为0
                          `task_status` int(11) DEFAULT NULL COMMENT '发布状态0未发布1发布中2发布完成3发布错误',+-->
            <template v-slot:status="{ row }">
              <div class="flex">
                <div v-show="row.taskStatus==2" class="success flex s-dai">成功</div>
                <div v-show="row.taskStatus==3" class="fail flex-column">
                  <i class="el-icon-warning" style="color: #FF4D4F;font-size: 16px"></i>
                  <span>失败</span>
                </div>
                <div v-show="row.taskStatus==0" class="s-dai">待发布</div>
                <!--<div v-show="row.taskStatus==1" class="s-dai">发布中</div>-->
              </div>
            </template>
            <!--执行信息-->
            <template v-slot:hint="{ row }">
              <!--              <div class="font-overflow" :style="row.taskStatus==3?'color:red':''">{{row.hint}}</div>-->
              <div class="font-overflow" :style="row.taskStatus==3?'color:red':''">{{row.taskStatus==2 ? '执行成功' : row.taskStatus==3 ? '执行失败' : ''}}</div>
            </template>
            <!--操作
            row.type==1：1D音2K手 -->
            <template v-slot:action="{ row }">
              <div class="flex-around">
                <el-link
                  :disabled="row.commentAmount && row.commentAmount > 0 ? false : true"
                  v-if="accountForm.type==1 || accountForm.type==2"
                  type="primary"
                  :underline="false"
                  @click.stop="viewComments(row)"
                >
                  查看评论
                </el-link>
                <!--<el-link
                  v-if="accountForm.type==1 || accountForm.type==2"
                  type="primary"
                  :underline="false"
                  @click.stop="viewComments(row)"
                >
                  手动补发
                </el-link>-->

                <!--:href="row.play_url"-->
                <el-link
                  :disabled="!row.videUrl"
                  type="primary"
                  :underline="false"
                  @click.stop="viewWorks(row)"
                >
                  观看作品
                </el-link>
                <el-link
                  v-if="accountForm.type==2"
                  type="danger"
                  :underline="false"
                  @click.stop="topClick(row)"
                >
                  置顶
                </el-link>
              </div>
            </template>
          </ele-pro-table>
        </div>
      </div>
    </el-drawer>
    <!-- 添加授权 ：静态图片 -->
    <el-dialog
      title="添加授权"
      :visible.sync="dialogVisible"
      :width="typeWidth"
      @close="dialogClose">
      <div class="flex-around flex-wrap">
        <div v-for="(i,j) in typeList" :key="j" :class="typeIndex==i.id  ? typeclass : isMouse==i.id ? typeclass2 : 'dy-icon'" class="flex" @click="typeClick(i.id)" @mouseover="mouseClick(i.id)" @mouseout="mouseLeave()" v-if="i.isShow==true">
          <img :src="i.img" style="width: 130px; height: 37px" />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogClose">取 消</el-button>
        <el-button type="primary" @click="dialogShow">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 重新授权 -->
    <el-dialog
      title="重新授权"
      :visible.sync="againEmpower"
      width="446px">
      <div class="flex-align-center"><i class="el-icon-success i-class"></i>请使用用户昵称为【{{codeInfo.nickname}}】扫码!</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="empowerClose">取 消</el-button>
        <el-button type="primary" @click="empowerConfirm">确 定</el-button>
        </span>
    </el-dialog>
    <!--    K手/D音 ‘静态’授权二维码-->
    <static-code ref="staticDialog" :type="typeIndex"></static-code>
    <!--    D音授权二维码-->
    <scan-code ref="codeDialog" :codeInfo="codeInfo"></scan-code>
    <!--D音cookie 授权二维码-->
    <cookie-code ref="cookieDialog" ></cookie-code>

    <!-- 检验状态 -->
    <ele-modal
      width="350px"
      :visible.sync="visible"
      :close-on-click-modal="true"
      custom-class="ele-dialog-form"
      title="一键检测登录状态"
    >
      <div class="workplace-goal-group flex-column">
          <el-progress :width="150" :percentage="100" type="circle" :format="() => ''" />
           <div class="workplace-goal-content flex-column">
        <!--               <i class="el-icon-success icon-size"></i>-->
               <div class="workplace-goal-num ele-text-heading">0/1</div>
      </div>
        <div class="flex-column progress-hint">
          <div>成功：1</div>
          <div>失败：0</div>
        </div>
      </div>
    </ele-modal>
    <!-- 选择分组 -->
    <ele-modal
      width="600px"
      :visible.sync="gruopValue"
      :close-on-click-modal="true"
      custom-class="ele-dialog-form"
      title="选择分组"
    >
      <div v-if="groupList.length>0">
        <div class="flex-columns">
          <el-input clearable prefix-icon="el-icon-search" style="width: 240px;margin-bottom: 20px" v-model="initInfo.groupName" placeholder="请输入需要搜索的分组名称" @change="init"></el-input>
          <!--groupInput 需是数组-->
          <el-scrollbar
            style="height: 156px"
            wrapStyle="overflow-x: hidden;"
            viewStyle="padding: 14px 10px;"
          >
            <div class="flex-wrap">
              <el-radio-group v-model="groupChecked" @change="selGroupClick(city)" v-for="city in groupList" :key="city.id">
                <el-radio class="radio-mbtn" style="min-width: 50px;margin-right: 20px;" :label="city.id">{{city.groupName}}</el-radio>
              </el-radio-group>
            </div>
          </el-scrollbar>
        </div>
        <div class="btn-all flex">
          <el-button size="small" @click="groupClose">取消</el-button>
          <el-button type="primary" size="small" @click="confirm()">确定</el-button>
        </div>
      </div>

      <!--没有分组时-->
      <div v-else class="flex-column m-margin15">
        暂无分组
        <el-button class="m-top10" type="primary" @click="addGroup()">去添加</el-button>
      </div>
    </ele-modal>
    <!--查看评论-->
    <seeComment ref="comments" :visible.sync="isComments" :commentId="commentId"></seeComment>
  </ele-pro-table>
</template>

<script>
  import {
    updateAccount,
    delAccount,
    ksPhotoList,
    dyPhotoList,
    douyinCheck,
    accountQuery,
    accountCode, kuaishouCode,accountCookie,accountH5
  } from "@/api/matrixManage/accountList";
  import {getEventDetails, getEventDetailsList, publishPage} from '@/api/releaseManage/tiktok';
  import scanCode from "./scan-code";
  import cookieCode from "./cookie-code";
  import staticCode from "./static-code";
  // import html from "./html"
  import {matrixDataRefresh, queryGroup} from "@/api/matrixManage/groupManage";
  import {query} from "@/api/agent/pointAllocation";
  import seeComment from "@/views/matrixManage/releaseManage/publishList/components/see-comments";
  export default {
    components:{scanCode,staticCode,seeComment,cookieCode},
    props: {
      // 表格数据
      accountForm: Object,
    },

    computed: {
      // 计算实付款
      isEmpower() {
        return function(row){			//使用函数返回
          let isEmpower = false;
          // true,已授权 ,为false，则为已失效
          // row.type  1D音2K手
          if(row.type==1){
            isEmpower = new Date(this.msToDate(new Date()).hasTime.replace(/-/g,"\/")) < new Date(this.date(row.createTime,row.expiresIn).replace(/-/g,"\/"))
          }
          if(row.type==2){
            isEmpower = new Date(this.msToDate(new Date()).hasTime.replace(/-/g,"\/")) < new Date(this.date(row.createTime,row.refreshExpiresIn).replace(/-/g,"\/"))
          }
          return isEmpower;
        }
      }
    },
    created(){
      console.log("进入账户列表格groupList",this.groupList)
      // 查询回显
      query({
        // oemId:this.$store.state.user.info.oemId,
        merchantId: this.$store.state.user.info.merchantId,
      }).then((msg) => {
        // if(msg.data != null){
        console.log("msg=========",msg)
        let info = localStorage.getItem('indexData') ? JSON.parse(localStorage.getItem('indexData')) : {};
        //（1.开启 2.发布）
        // 1.抖音h5 2.抖音无痕（cookie） 3.抖音代员工 4.快手、
        if(info && info.toCookieReleased==1){
          let item={img:require('/src/assets/dyCookie.png'),id:2,
            isShow:true}
          this.typeList.splice(1, 0, item);
          // this.checkList.push('D音H5任务发布')
          console.log('D音cookie发布this.form333========')
        }
        if(info && info.toBeReleased==1){
          let item={img:require('/src/assets/dyStaff.png'),id:3,isShow:true}
          this.typeList.splice(1, 0, item);
          // this.checkList.push('代员工发布到D音')
          console.log("代员工发布到D音333")
        }
        // }
        this.typeWidth=(this.typeList.length*190+50*this.typeList.length)+'px'
        console.log("this.typeWidth",this.typeWidth)
      })
        .catch((e) => {
          this.$message.error(e);
        });
    },
    data() {
      return {
        types: 1,
        loading: false,  // 用于表格加载
        groupList:[],
        url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
        typeList:[
          // 0： cookie发布(默认)   1： h5发布   2： 代员工发布   3：快手发布(默认）
          // {img:require('/src/assets/dyCookie.png'),id:0},
          {img:require('/src/assets/dyH5.png'),id:1,
            isShow:true},
          // {img:require('/src/assets/dyStaff.png'),id:2},
          {img:require('/src/assets/ks.png'),id:4,
            isShow:true}
        ],
        groupInput:[],
        groupChecked:[],
        form:{},
        // 是否展示分组弹框
        gruopValue: false,
        visible: false,
        // 新增授权
        dialogVisible: false,
        // 重新授权
        againEmpower:false,
        // 当前编辑数据
        current: {},
        // 是否显示编辑弹窗
        showEdit: false,
        // Drawer 打开的方向
        direction: 'rtl',
        stautsIndex:'',
        // 0未发布1发布中2发布完成3发布错误
        stautsList :[
          {
            name:'全部',
            id:''
          },
          {
            name:'待发布',
            id:0
          },
          /*{
            name:'发布中',
            id:1
          },*/
          {
            name:'发布成功',
            id:2
          },
          {
            name:'发布失败',
            id:3
          }
        ],
        // 表格列配置
        childColumn: [
          // 复选框选择
          {
            columnKey: 'selection',
            type: 'selection',
            width: 45,
            align: 'center'
          },
          {
            prop: 'title',
            label: '标题',
            align: 'center',
            showOverflowTooltip: true,
            slot: 'nickname'
          },
          {
            slot: 'playCount',
            prop: 'view_count',
            label: '曝光量',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            slot: 'diggCount',
            prop: 'like_count',
            label: '点赞数',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            slot: 'commentCount',
            prop: 'comment_count',
            label: '评论数',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            slot: 'status',
            prop: 'pending',
            label: '发布状态',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            slot: 'hint',
            prop: 'hint',
            label: '执行信息',
            align: 'center',
            showOverflowTooltip: true,
            show: false
          },
          {
            prop: 'publishTime',
            label: '(待)发布时间',
            width:180,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            label: '操作',
            columnKey: 'action',
            width: 230,
            align: 'center',
            resizable: false,
            slot: 'action',
            hideInSetting: true,
            showOverflowTooltip: true,
            fixed: 'right'
          }
        ],
        //status 发布状态 1：成功，2s失败 （作品查询list）
        /* childUsers: [
         ],*/
        // 选中数据
        childSelect: [],
        // 表格选中数据
        selection: [],
        // 表格列配置
        columns: [
          {
            columnKey: 'selection',
            type: 'selection',
            width: 45,
            align: 'center'
          },
          {
            prop: 'head',
            label: '头像',
            align: 'center',
            showOverflowTooltip: true,
            slot: 'head',
            // show:false
          },
          {
            prop: 'nickname',
            label: '用户昵称',
            align: 'center',
            showOverflowTooltip: true,
          },
          {
            prop: 'exposureAmount',
            // prop: 'playCount',
            label: '曝光量',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (_row, _column, cellValue) => {
              return cellValue ? cellValue : '0';
            }
          },
          {
            prop: 'upvoteAmount',
            // prop: 'diggCount',
            label: '点赞数',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (_row, _column, cellValue) => {
              return cellValue ? cellValue : '0';
            }
          },
          {
            prop: 'commentAmount',
            // prop: 'commentCount',
            label: '评论数',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (_row, _column, cellValue) => {
              return cellValue ? cellValue : '0';
            }
          },
          {
            prop: 'createTime',
            label: '授权状态/预计到期时间',
            align: 'center',
            width:180,
            showOverflowTooltip: true,
            slot:'createTime'
          },
          {
            prop: 'groupName',
            label: '账号分组',
            align: 'center',
            showOverflowTooltip: true,
            slot: 'groupName',
            show:true
          },
          {
            prop: 'fansManage',
            label: '挂载橱窗',
            align: 'center',
            showOverflowTooltip: true,
            slot:'fansManage',
            show: false
          },
          {
            prop: 'authExTime',
            label: 'cookie状态/预计到期时间',
            align: 'center',
            showOverflowTooltip: true,
            slot:'authExTime',
            show: false
          },
          {
            label: '操作',
            columnKey: 'action',
            width: 230,
            align: 'center',
            resizable: false,
            slot: 'action',
            hideInSetting: true,
            showOverflowTooltip: true,
            fixed: 'right'
          }
        ],
        // 选中数据
        select: [],
        // 是否展示授权二维码
        codeShow:false,
        // D音二维码
        code:'',
        // ‘无痕扫码’ 用户名
        codeInfo:{},
        dataInfo:{},
        // K手/D音 授权选择样式
        typeclass:'',
        typeclass2:'',
        // 是否鼠标hover
        isMouse:-1,
        typeIndex:-1,
        username:this.$store.state.user.info.username,
        initInfo:{
          username:this.$store.state.user.info.username,
          limit:10,
          page:1
        },
        accountLists:[],
        playCount:0,//曝光量
        diggCount:0,//点赞数
        commentCount:0,//评论数
        typeWidth:'',  // ‘添加授权’对话框，宽度
        isReauthorization:false, //是否重新授权（true则不展示‘快手’类型

        // 是否弹出“查看评论”弹出框
        isComments:false,
        // 查看评论——用户id
        commentId:null,
        // 账号列表——查询作品——list
        parms:{}
      };
    },
    methods: {
      showType(type){
        console.log("types=============",type)
        console.log("columns=============",this.columns)
        this.types=type
        // 根据条件判断隐藏
        this.columns[8].show=type==2 ? true : false
        this.columns[9].show=type==2 ? true : false
        // 账号分组
        // this.columns[7].show=type==4 ? false : true
        // 抽屉——作品
        this.childColumn[6].show=type==2 ? true : false

      },
      // 初始化分组
      init(){
        if(!this.initInfo.groupName){
          delete this.initInfo.groupName
        }
        this.initInfo.groupType=this.accountForm.type
        console.log('this.initInfo',this.initInfo)
        queryGroup(this.initInfo)
          .then((data) => {
            this.groupList=data.list
            console.log(' this.groupList--', this.groupList)
          })
          .catch((e) => {
            this.$message.error(e);
          });
      },
      // 添加分组
      addGroup(){
        this.$router.push({path:'/matrixManage/accountManage/groupManage'})
        this.gruopValue=false
      },
      /* 刷新————表格数据源 */
      // datasource({ page, limit, where, order }) {
      //   return accountQuery({ ...where, ...order, page, limit });
      // },
      /* 如果想在数据源里面获取到接口返回的数据, 增加 async 和 await */
      async datasource({ page, limit, where, order }) {
        console.log(" this.accountFormAAAAAAAAAAAAAAAAAAAAAAA", this.accountForm)
        let parms={}
        parms.type= this.accountForm.type == 4 ? 2 : 1
        parms.types= this.accountForm.type
        parms.username= this.username
        if(this.accountForm.authStatus || this.accountForm.authStatus==0){
          parms.authStatus= this.accountForm.authStatus
        }
        if(this.accountForm.groupId){
          parms.groupId= this.accountForm.groupId
        }
        if(this.accountForm.startTime){
          parms.startTime= this.accountForm.startTime
          parms.endTime= this.accountForm.endTime
        }

        const result = await accountQuery({ ...where, ...order, page, limit,...parms });
        console.log("result============",result)
        this.accountLists=result.list
        return result;  // 这里返回的数据要包含 list 和 count 两个字段，字段名称可以通过 response 属性配置
      },
      /* 刷新表格 */
      reload(where) {
        this.$refs.table.reload({ page: 1, where: where });
      },
      // date:创建日期 time：授权过期时间（需加）
      date (date,addTime) {
        // 日期或中国标准时间转毫秒数：
        let result = new Date(date).getTime();
        let allDate=result+addTime*1000 // 按秒计算，所以需要*1000（原始毫秒）
        // 预计到期时间计算
        let endtime= this.msToDate(allDate).hasTime
        // 去除秒数截取最后：的前面数字
        let index = endtime .lastIndexOf(":")
        endtime =endtime .substring(0,index);
        return endtime
      },
      // 毫秒数或中国标准时间转日期
      msToDate (msec) {
        let datetime = new Date(msec);
        let year = datetime.getFullYear();
        let month = datetime.getMonth();
        let date = datetime.getDate();
        let hour = datetime.getHours();
        let minute = datetime.getMinutes();
        let second = datetime.getSeconds();
        let result1 = year +
          '-' +
          ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
          '-' +
          ((date + 1) < 10 ? '0' + date : date) +
          ' ' +
          ((hour + 1) < 10 ? '0' + hour : hour) +
          ':' +
          ((minute + 1) < 10 ? '0' + minute : minute) +
          ':' +
          ((second + 1) < 10 ? '0' + second : second);

        let result2 = year +
          '-' +
          ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
          '-' +
          ((date + 1) < 10 ? '0' + date : date);

        let result = {
          hasTime: result1,
          withoutTime: result2
        };

        return result;
      },
      // 添加授权
      typeClick(e){
        console.log("进入添加授权class=========",e)
        //1.抖音h5 2.抖音无痕 3.抖音代员工 4.快手 typeIndex相关联也需修改
        this.typeIndex=e
        this.typeclass=e==4?'sel-ks':'sel-dy'
      },
      mouseClick(e){
        console.log("mouseClickclass=========",e)
        this.isMouse=e
        this.typeclass2=e==4?'sel-ks':'sel-dy'
      },
      mouseLeave(){
        this.isMouse=-1
      },
      // 选择分组
      selGroupClick(e){
        console.log("选择分组e=========",e,'this.groupInput',this.groupInput)
        // 需修改 暂时只能单选分组
        this.form.groupId=e.id
        this.form.groupName=e.groupName
        this.form.area=e.area
      },
      updateVisible(value){
        console.log("value",value)
        this.visible = value
      },
      // 关闭授权弹框(需清空样式）
      dialogClose(){
        this.dialogVisible = false
        setTimeout(()=>{
          this.typeList[this.typeList.length-1].isShow=true
          this.typeWidth=(this.typeList.length*190+50*this.typeList.length)+'px'
        },300)
      },
      // 打开获取 “D音/K手” 静态二维码
      dialogShow() {
        if(this.typeIndex<0){
          this.$message.warning('请选择授权的类型')
          return
        }
        this.dialogClose()
        // this.$refs['staticDialog'].show()
        this.show()
      },
      async show(){
        let code=''
        console.log("this.typeIndex",this.typeIndex)
        if(this.typeIndex==3 || this.typeIndex==1 || this.typeIndex==2){
          //1.抖音h5 2.抖音无痕 3.抖音代员工 4.快手
          code = this.typeIndex==2 ? await accountCookie(this.username,this.$store.state.user.info.merchantId)
            : this.typeIndex==1 ? await accountH5(this.username,this.$store.state.user.info.merchantId)
              : await accountCode(this.username,this.$store.state.user.info.merchantId)
          // accountCookie,accountH5,accountCode
          // 获取D音静态二维码
          // code =await api(this.$store.state.user.info.username)
          console.log("code===============",code,code.data)
          if(this.typeIndex==2){
            this.$refs['cookieDialog'].show()
          }
          else{
            window.open(code.data)
          }
        }
        if(this.typeIndex==4){
          // 视频号二维码跳转
          var host =window.location.host;
          // var host ='oemkk.weijuyunke.com';
          let url = 'https://'+host+'/H5/argescreen_index.html#/?username='+this.$store.state.user.info.username+'&merchantId='+this.$store.state.user.info.merchantId
          window.open(url)
          // this.$refs['staticDialog'].show()
          // 获取K手静态二维码
          // code =await kuaishouCode(this.$store.state.user.info.username)
        }
      },
      // 取消“重新授权”
      empowerClose(){
        this.againEmpower=false
      },
      // 确定 “重新授权”
      empowerConfirm(){
        this.$refs['codeDialog'].show()
        this.empowerClose()
      },
      // “作品” 弹出框，筛选状态事件
      stautsClick(index){
        this.stautsIndex=index
        this.getPublishPage(this.current)
      },
      // 添加授权
      addAccredit(){
        this.typeIndex=-1
        this.dialogVisible=true
      },
      // 检验状态
      inspectionStatus(){
        let ids=[]
        this.accountLists.filter((item) => {
          //台本 'x' in obj
          if (item.type==1) {
            ids.push(item.id)
          }
        });
        // let ids=this.accountLists.map(item => {
        //   return item.type==1 ? item.id :void  0
        // })
        console.log('ids---------',ids)
        // 校验D音自研接口授权是否过期
        douyinCheck({
          ids:ids
        })
          .then((data) => {
            // this.$emit('load')
            this.reload()
            this.$message.success(data.msg);
          })
          .catch((e) => {
            this.$message.error(e);
          });
        this.updateVisible(true)
      },
      // 删除
      delMoreAccount(){
        if (!this.selection.length) {
          // 请选择需要操作的数据
          this.$message.error('请选择数据');
          return;
        }
        var ids=this.selection.map(item => {
          return item.id
        })
        console.log('删除点击事件his.selection===', this.selection ,'ids',ids)
        this.delAccounts(ids)
        // this.$emit('done', this.selection);
      },
      /* 打开作品 */
      worksClick (row) {
        let stauts=false
        console.log('点击了作品时间',row)
        this.current = row;  // 表格的行数据赋值给 current
        if(row.type==1){
          stauts= new Date(this.msToDate(new Date()).hasTime.replace(/-/g,"\/")) >= new Date(this.date(row.createTime,row.expiresIn).replace(/-/g,"\/"))
        }
        if(row.type==2){
          stauts= new Date(this.msToDate(new Date()).hasTime.replace(/-/g,"\/")) >= new Date(this.date(row.createTime,row.refreshExpiresIn).replace(/-/g,"\/"))
        }
        if(stauts){  // 已过期
          this.$message.error('当前账号授权已失效,请重新授权！')
          return
        }
        this.stautsClick(0)
        this.showEdit = true;
      },
      // 数据刷新
      dataRefresh(){
        this.loading=true
        matrixDataRefresh(this.parms)
          .then((data) => {
            this.$message.success('刷新成功!');
            //查询当前账号所有作品数据
            this.allGetNum()
            if(this.parms.dyAccountId){
              this.$nextTick(()=>{
                this.$refs['tableChild'].reload()
              })
            }
            this.loading=false
          })
          .catch((e) => {
            this.loading=false
            this.$message.error(e);
          });
      },
      // 查询用户“作品”list总数
      allGetNum(){
        getEventDetailsList(this.parms)
          .then((data) => {
            this.playCount=0
            this.diggCount=0
            this.commentCount=0
            console.log("进入作品分页查询====",this.parms,'data',data)
            let list=data
            for(let i=0;i<list.length;i++){
              if(list[i].taskStatus!=0 ){
                let exposureAmount=list[i].exposureAmount ? list[i].exposureAmount : 0
                let upvoteAmount=list[i].upvoteAmount ? list[i].upvoteAmount : 0
                let commentAmount=list[i].commentAmount ? list[i].commentAmount : 0
                this.playCount+=exposureAmount   //曝光数
                this.diggCount+=upvoteAmount   //点赞数
                this.commentCount+=commentAmount   //评论数
              }
            }
          })
          .catch((e) => {
            this.$message.error(e);
          });
      },
      async childUsers({ page, limit, where, order }) {
if(!this.parms.dyAccountId){
  return
}
        console.log("进入作品分页查询====",this.parms)
        const result = await getEventDetails({ ...where, ...order, page, limit,...this.parms });
        console.log('result:', result);


        this.loading=false  // 关闭表格过渡中
        return result;  // 这里返回的数据要包含 list 和 count 两个字段，字段名称可以通过 response 属性配置
      },
      getPublishPage(row){
        this.loading=true  // 展示表格过渡中
        this.parms={
          dyAccountId:row.id, // 用户id
          types:this.accountForm.type, //账号所属 1.抖音h5 2.抖音无痕（cookie） 3.抖音代员工 4.快手
          /*page: 1,// 分页参数 *必需
          limit: 10, // 每页展示多少数量  *必需*/
        }
        if(this.stautsIndex!=0){
          // 发布状态(taskStatus): 0未发布1发布中2发布完成3发布错误
          this.parms.taskStatus=this.stautsList[this.stautsIndex].id
        }
        //查询当前账号所有作品数据
        this.allGetNum()
        if(this.parms.dyAccountId){
          this.$nextTick(()=>{
            this.$refs['tableChild'].reload()
          })
        }
      },
      /* 批量分组 */
      allGroups(){
        if (!this.selection.length) {
          // 请选择需要操作的数据
          this.$message.error('请选择数据');
          return;
        }
        this.form.id=this.selection.map(item => {
          return item.id
        })
        this.groupChecked= []
        this.gruopValue = true
        this.init()
        // 清空分组数据
        this.groupInput=[]
        console.log('批量分组点击事件his.selection===', this.selection )

        // if(!this.initInfo.groupName){
        //   delete this.initInfo.groupName
        // }
        // this.initInfo.groupType=this.accountForm.type

      },
      /* 分组 */
      groupClick(e){
        this.groupChecked=e ? e.groupId : []
        console.log("分组e---------------",e)
        this.form.id=[e.id]
        this.gruopValue = true
        this.init()
        // 清空分组数据
        this.groupInput=[]
      },
      // 确定分组
      confirm(){
        console.log("确定分组this.form====",this.form)
        if(!this.groupChecked){
          this.$message.error('请先选择分组')
          return
        }
        if(this.groupChecked && !this.form.groupId){
          this.$message.error('账号已在该分组中')
          return
        }
        console.log('this.form.id',this.form.id)
        let groupList=[]
        if(this.form.id.length==1){
          let groupInfo={}
          groupInfo.id=this.form.id[0]
          groupInfo.groupId=this.form.groupId
          groupInfo.groupName=this.form.groupName
          groupInfo.area=this.form.area
          groupList.push(groupInfo)
        }
        else{
          console.log("进入多选",this.form.id.length)
          for(let i=0;i<this.form.id.length;i++){
            let groupInfo={}
            console.log("this.form[i]",this.form.id[i])
            groupInfo.id=this.form.id[i]
            groupInfo.groupId=this.form.groupId
            groupInfo.groupName=this.form.groupName
            groupInfo.area=this.form.area
            console.log("groupInfo",groupInfo)
            groupList.push(groupInfo)
            console.log("筛选完成的111groupList",groupList)
          }
        }
        console.log("筛选完成的2222groupList",groupList)
        updateAccount(groupList)
          .then((data) => {
            // this.$emit('load')
            this.groupClose()
            this.reload()
            this.$message.success('分组成功！');
          })
          .catch((e) => {
            this.$message.error(e);
          });
      },
      groupClose(){
        this.gruopValue = false
        delete this.initInfo.groupName
      },
      /* 无痕授权 */
      reauthorization(e) {
        console.log("无痕授权e---",e)
        if(!e.groupId){
          this.$message.warning('请先选择分组')
          return
        }
        this.codeInfo=e
        this.againEmpower=true
        // 编辑弹窗编辑完成后 done 事件回传表单数据，使用 Object.assign 赋值给 current 即可修改表格的行数据
        // if(this.current) {
        //   Object.assign(this.current, form);
        // }
      },
      /* 单个删除 */
      delUser(row) {
        console.log("单个删除",row)
        let ids=[]
        ids.push(row.id)
        console.log("ids====",ids)
        this.delAccounts(ids)
      },
      // 重新授权
      reauthorizationMore(row){
        console.log("row",row)
        // 1：抖音 2：快手
        if(row.type==1){
          this.addAccredit()
          // 隐藏‘快手’类型展示
          this.typeList[this.typeList.length-1].isShow=false
          this.typeWidth=(2*190+50*2)+'px'
        }
        if(row.type==2){
          this.typeIndex=4
          setTimeout(()=>{
            // this.$refs['staticDialog'].show()
            var host =window.location.host;
            // var host ='oemkk.weijuyunke.com';
            let url = 'https://'+host+'/H5/argescreen_index.html#/?username='+this.$store.state.user.info.username+'&merchantId='+this.$store.state.user.info.merchantId
            window.open(url)
          },300)
        }
      },
      delAccounts(ids){
        this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delAccount({
            ids:ids
          })
            .then((data) => {
              this.reload()
              // this.$emit('load')
              this.$message.success('删除成功!');
            })
            .catch((e) => {
              this.$message.error(e);
            });
        }).catch(() => {
          this.$message.info('已取消删除');
        });
      },
      // 查看评论
      viewComments(row){
        console.log("点击了查看评论")
        this.commentId=row.id
        this.isComments=true
        this.$nextTick(()=>{
          this.$refs['comments'].reload()
        })
      },
      // 观看作品
      viewWorks(row){
        console.log("点击了观看作品")
        // this.accountForm.type, //账号所属 1.抖音h5 2.抖音无痕（cookie） 3.抖音代员工 4.快手
        // let videoUrl =  this.accountForm.type==4 ? row.doyiDate.list[0].share_url : row.videoUrl
        let videoUrl =   row.videUrl
        window.open(videoUrl)
      },
      // 置顶
      topClick(){
        console.log("点击了置顶")
      }
    }
  };
</script>
<style scoped lang="less">
  /*‘单选框’转‘多选框’样式*/
  /*  /deep/ .el-radio__inner {
      border-radius: 2px !important;
    }

    /deep/ .el-radio__input.is-checked .el-radio__inner::after {
      content: '';
      width: 8px;
      height: 3px;
      border: 1px solid white;
      border-top: transparent;
      border-right: transparent;
      text-align: center;
      display: block;
      position: absolute;
      top: 3px;
      left: 2px;
      transform: rotate(-45deg);
      border-radius: 0px;
      background: none;
    }*/

  .btn-class{
    margin: 10px 0;
    .el-button{
      padding: 0;
      width: 94px;
      border-radius: 2px;
      height: 33px;
    }
  }
  .top-padding{
    padding: 32px 32px 55px;
    .avatar{
      width: 50px;
      height: 50px;
      border-radius: 50%;
      margin-right: 19px;
    }
    .end-time{
      margin-top: 15px;
      color: #757575;
      .empower{
        margin:0 16px 0 4px;
        color: #31A952;
      }
      .expire{
        margin:0 16px 0 4px;
        color: #d03050;
      }
    }
    .numberCount{
      width: calc(100% / 3);
      span{
        color: #757575;
      }
      div{
        margin-top: 11px ;
        color: #1E6CEB;
        font-size: 32px;
      }
    }
  }
  /*数据刷新 按钮*/
  .btn-refresh{
    background: #1E6CEB;
    border-radius: 2px;
    margin: 0 31px 17px;
  }
  .m-table{
    margin: 0 28px 0 24px;
    .stauts-class,.sel-stauts-class{
      font-size: 16px;
      margin:0 52px 0 26px;
      padding: 23px 0px 15px;
      line-height: 19px;
    }
    .stauts-class{
      color: #757575;
    }
    .sel-stauts-class{
      color: #1E6CEB;
      border-bottom:3px solid #1E6CEB;
      box-sizing: border-box;
      -moz-box-sizing: border-box;
    }
    /* 置顶 样式*/
    .top-class{
      width: 43px;
      color: #1E6CEB;
      font-size: 12px;
      background: #DDF0FF;
      border-radius: 2px;
    }
    /*成功*/
    .success{
      width: 57px;
      height: 27px;
      background: #DDF0FF;
      border-radius: 2px;
    }
    /*待发布*/
    .s-dai{
      color: #1E6CEB;
    }
    /*失败*/
    .fail{
      color: #757575;
    }
  }
  .v-icon ,.expired-icon{
    padding: 1px 7px;
    border-radius: 2px;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    /*font-size: 14px;*/
  }
  .v-icon{
    color: #18a058;
    background-color: rgba(24, 160, 88, 0.1);
    border: 1px solid rgba(24, 160, 88, 0.3);
  }
  .expired-icon{
    color: #d03050;
    background-color: rgba(208, 48, 80, 0.08);
    border: 1px solid rgba(208, 48, 80, 0.23);
  }
  .i-class{
    margin-top: 2px;
    font-size: 20px;
    color: rgb(24, 160, 88);
  }
  .sel-dy:hover,.sel-ks:hover{
    transform: scale(1.1);
    transition: 0.8s all linear;
  }
  /*添加授权*/
  .dy-icon,.sel-dy,.sel-ks{
    color: #fff;
    margin: 5px 0px;
    /*margin: 5px 30px;*/
    background: #b3abab;
    width: 188px;
    height: 100px;
    text-align: center;
    line-height: 100px;
    border-radius: 15px;
    cursor: pointer;
    transition: 0.8s all linear;
  }
  .sel-dy{
    background: #000;
  }
  .sel-ks{
    background: linear-gradient(rgb(251, 152, 0) 0%, rgb(243, 120, 3) 100%);
  }
  /*一键检测登录状态*/
  .workplace-goal-group{
    position: relative;
    .workplace-goal-content{
      .icon-size{
        position: absolute;
        top: 58px;
        font-size: 40px;
        color:rgb(32, 160, 255);
      }
      div{
        position: absolute;
        top: 68px;
        font-size: 18px;
        color: #a1a1a1;
      }
    }
    .progress-hint{
      color: #000;
      padding: 20px 0 10px;
      div{
        margin-bottom: 6px;
      }
    }
  }
  .btn-all{
    margin:50px 0 20px
  }
</style>
